<template>
  <div>
    <Header :isGoBack="false" :class="isHeaderFixed ? 'fixed-header-shadow' : 'fixed-header'">
      <template v-slot:left>
        <div>
          {{ checkedBookData.edition_name }}- {{ checkedBookData.grade_name }} >
          闯关测试
        </div>
      </template>
      <template v-slot:right>
        <div class="test-btn" v-if="paperData.isAnswer">
          <span class="btn-bg ml20">
            <el-button class="button button-bg-second" @click="studyContinue">继续</el-button>
          </span>

          <span class="btn-bg ml20">
            <el-button class="button button-border-second" @click="goQuestionCenter">
              退出
            </el-button>
          </span>
        </div>
        <div class="test-btn" v-else>
          <span v-if="paperData.eng_question_form_vo_list">时间: {{ testTime | filterTime }}</span>
          <span class="btn-bg ml20" v-if="paperData.eng_question_form_vo_list">
            <el-button class="button button-bg-second" @click="submitPaper">交卷</el-button>
          </span>
          <span class="btn-bg ml20">
            <el-button class="button button-border-second" @click="goStudyCenter">
              退出
            </el-button>
          </span>
        </div>
        <!-- <div class="test-btn">
          <span>计时：{{ testTime | filterTime }}</span>
          <span class="btn-bg ml20">
            <el-button class="yellow-bg" @click="submitPaper">交卷</el-button>
          </span>
          <span class="btn-bg ml20">
            <el-button class="yellow-border" @click="goStudyCenter">
              返回学习中心
            </el-button>
          </span>
        </div> -->
      </template>
    </Header>
    <div class="general-test-box">
      <div class="w1200 question-test-paper question-fixed">
        <div class="general-test reading-question question-left">
          <div class="question-type-container" v-for="(quetionType, index) in questionList" :key="quetionType.type">
            <div class="type-title">
              <span>{{ index + 1 }}.</span>
              {{ quetionType.type == 1 ? "单项选择" : "填空题" }}
              <span>
                <!-- <span class="reminder-text">(提示文字)</span> -->
              </span>
            </div>
            <!-- question-list -->
            <ul class="reading-question-list">
              <li class="question" :class="question.allIndex == nowIndex
                ? 'question-ing '
                : question.studentAnswer
                  ? 'checked-question'
                  : ''
                " v-for="(question, index2) in quetionType.question_list"
                :key="question.questionId + '' + question.answerType">
                <i v-if="question.isAnswer && quetionType.type == 1"
                  @click="readCollect(question.questionId, index2, question, quetionType.type)"
                  :class="[defaultStart[index2] ? 'el-icon-star-on' : 'el-icon-star-off']" class="start"
                  style="color: rgb(241, 209, 149); cursor: pointer;font-size: 20px;"></i>
                <i v-if="question.isAnswer && quetionType.type != 1"
                  @click="readCollect(question.questionId, index2, question, quetionType.type)"
                  :class="[typesStart[index2] ? 'el-icon-star-on' : 'el-icon-star-off']" class="start"
                  style="color: rgb(241, 209, 149); cursor: pointer;font-size: 20px;"></i>
                <Question :nowIndex="index2 + 1" :question="question" :isAnswer="paperData.isAnswer"
                  :ref="`question-${index}-${index2}`" :classify="5"></Question>
              </li>
            </ul>
          </div>
        </div>
        <div class="question-right">
          <div class="question-right-header">
            <h4>题目序号</h4>
            <p>
              <span class="answered">已答</span>
              <span class="not-answered">未答</span>
            </p>
          </div>
          <div class="question-right-container scrollbar">
            <div class="">
              <div class="" v-for="(quetionType, index) in questionList" :key="index">
                <h4 class="type-title">
                  {{ quetionType.type == 1 ? "单项选择" : "填空题" }}
                </h4>
                <div class="list-num">
                  <div class="list-num-item" :class="question.studentAnswer.length > 0 ? 'answered-item' : ''
                    " v-for="(question, index2) in quetionType.questionList" :key="index2">
                    {{ index2 + 1 }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="question-right" v-if="paperData.isAnswer">
          <div class="question-right-header question-right-score">
            <h4>答题成绩</h4>
            <div class="score">
              <span>{{ paperData.score }}</span>分
            </div>
            <div class="info">
              <div class="time">
                考试用时：
                <span>{{ testTime | filterTime }}</span>
              </div>
              <div class="time" v-if="paperData.integral">
                学币：
                <span>+{{ paperData.integral }}</span>
              </div>
            </div>
          </div>
          <div class="question-right-header">
            <h4>题目序号</h4>
            <p>
              <span class="right">正确</span>
              <span class="wrong">错误</span>
            </p>
          </div>
          <div class="question-right-container scrollbar">
            <div class="">
              <div class="" v-for="(quetionType, index) in questionList" :key="index">
                <h4 class="type-title">
                  {{ quetionType.type == 1 ? "单项选择" : "填空题" }}
                </h4>
                <div class="list-num">
                  <div class="list-num-item" :class="question.is_true ? 'right-item' : 'wrong-item'"
                    v-for="(question, index2) in quetionType.question_list" :key="index2">
                    {{ index2 + 1 }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="question-right" v-else>
          <div class="question-right-header">
            <h4>题目序号</h4>
            <p>
              <span class="answered">已答</span>
              <span class="not-answered">未答</span>
            </p>
          </div>
          <div class="question-right-container scrollbar">
            <div class="">
              <div class="" v-for="(quetionType, index) in questionList" :key="index">
                <h4 class="type-title">
                  {{ quetionType.type == 1 ? "单项选择" : "填空题" }}
                </h4>
                <div class="list-num">
                  <div class="list-num-item" :class="question.studentAnswer.length > 0 ? 'answered-item' : ''
                    " v-for="(question, index2) in quetionType.question_list" :key="index2">
                    {{ index2 + 1 }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <PlayVoiceAudio ref="playVoiceAudio"></PlayVoiceAudio>
  </div>
</template>
<script>
import Header from "@/components/Header";
import { getQuestionPaper, checkQuestionPaper } from "@/api/question";
import Question from "@/components/Question.vue";
import PlayVoiceAudio from "@/components/PlayVoiceAudio.vue";
import { addStudentCollectionQuestion, deleteStudentCollectionQuestion } from "@/api/individuationRead.js"
export default {
  data() {
    return {
      defaultStart: Array(30).fill(false),
      typesStart: Array(30).fill(false),
      paperData: {},
      questionList: [],
      typeObj: {
        0: "单项选择",
        1: "填空",
      },
      nowIndex: 0,
      allNum: 0,
      testTime: 0,
      testTimeTimer: null,
      checkedBookData: null,
      unitId: null,
      category: null,
      source: null,
      testLoading: false,
      isHeaderFixed: false,
      submitReminder: true,
      isOpenMessageBox: false,
    };
  },
  computed: {},

  methods: {
    readCollect(questionId, index, question, type) {
      console.log(question);
      let data = {
        question_type: question.answerType - 1,
        unit_id: this.unitId,
        book_id: this.checkedBookData.book_id,
        source_type: 4,
        link_id: questionId,
        source: 4,
        is_individ: 0
      }
      let typeName;
      if (type == 1) {
        typeName = "defaultStart"
      } else {
        typeName = "typesStart"
      }
      if (this[typeName][index] == true) {
        deleteStudentCollectionQuestion(data)
          .then(() => {
            this.$message({
              message: '已取消收藏',
              type: 'warning'
            });
            this.$set(this[typeName], index, false)
          })
          .catch(() => {
            console.log("失败");
          });
      } else {
        addStudentCollectionQuestion(data)
          .then((res) => {
            if (res.code == "200") {
              this.$message({
                message: '收藏成功',
                type: 'success'
              });
            }
            this.$set(this[typeName], index, true)
          })
          .catch(() => {
            console.log("失败");
          });
      }

    },
    printTest() {
      this.$print(this.$refs.printTest);
      // window.print();
    },
    goQuestionCenter() {
      this.$router.push({
        name: "questionStudyCenter",
      });
    },
    goStudyCenter() {
      this.$confirm(`试卷还未提交，是否退出`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        closeOnPressEscape: false,
      })
        .then(() => {
          this.goQuestionCenter();
        })
        .catch(() => {
          return false;
        });
    },
    studyContinue() {
      this.defaultStart = Array(30).fill(false),
        this.typesStart = Array(30).fill(false),
        this.testTime = 0;
      this.getTestPaper();
    },
    getTestPaper() {
      let data = {
        book_id: this.checkedBookData.book_id,
        unit_id: this.unitId,
        is_unusual: 0,
        question_type_list: [1, 7],
      };
      getQuestionPaper({ data }).then((res) => {
        if (res.code == 200) {
          res.data.eng_question_form_vo_list.forEach((questionTypeList) => {
            questionTypeList.question_list.forEach((question) => {
              let newTitle = question.title;
              question.oldTitle = question.title;
              question.inputNum = 0;
              if (questionTypeList.type == 7) {
                let index = 1;
                let pos = newTitle.indexOf("_____");
                while (pos !== -1) {
                  newTitle = newTitle.replace(
                    /_{5}/,
                    ` <input class='question-input' autocomplete="off" id='input-${question.id}-${index}' onpaste = "return false";></input> `
                  );
                  index++;
                  pos = newTitle.indexOf("_____");
                }
                question.inputNum = index - 1;
              }
              question.questionId = question.id;
              question.title = newTitle;
              question.answerType = question.type == 1 ? 1 : 7;
              question.answerList = question.option_list.map((item) => {
                return {
                  answer_id: item.id,
                  answer: item.answer,
                };
              });
              question.studentAnswer = [];
              // question.inputNum = question.inputNum;
            });
          });
          res.data.eng_question_form_vo_list = res.data.eng_question_form_vo_list.sort(
            (a, b) => {
              return a.type - b.type;
            }
          );
          this.paperData = res.data;
          this.paperData.isAnswer = false;
          console.log(this.paperData,"paperData");
          this.questionList = this.paperData.eng_question_form_vo_list;
          this.$nextTick(() => {
            this.addInputEvent();
          });
          this.timerFun();
        } else if (res.code == 405) {
          this.$alert("暂无试题", "消息提示", {
            confirmButtonText: "确定",
            callback: () => {
              this.goStudyCenter();
            },
          });
        }
      });
    },

    timerFun() {
      this.testTimeTimer = setInterval(() => {
        this.testTime++;
      }, 1000);
    },
    submitPaper() {
      let number = 0;
      this.questionList.forEach((questionType) => {
        questionType.question_list.forEach((question) => {
          if (
            !question.studentAnswer ||
            question.studentAnswer.length == 0 ||
            question.studentAnswer.some((item) => !item)
          ) {
            number++;
          }
        });
      });
      this.$confirm(
        `${number > 0 ? "还有" + number + "道题未答，" : ""}
        是否检查完毕，确认提交？`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }
      )
        .then(() => {
          this.postPaper();
        })
        .catch(() => {
          return false;
        });
    },
    postPaper() {
      this.testLoading = true;
      console.log(this.paperData,"yeghhj");
      this.paperData.eng_question_form_vo_list.forEach((questionType) => {
        questionType.question_list.forEach((question) => {
          try {
            for (let i = 0; i < question.inputNum; i++) {
              if (!question.studentAnswer[i]) {
                question.studentAnswer[i] = "";
              }
            }
            question.stu_answer_list = question.studentAnswer.map(
              (answer, answerIndex) => {
                if (question.answerType == 1) {
                  return {
                    answer_id: answer,
                  };
                } else {
                  let answerData = question.option_list.filter((item) => {
                    return item.order_index == answerIndex + 1;
                  });
                  return {
                    answer_id: answerData[0] ? answerData[0].id : null,
                    stu_answer: answer.trim(),
                    order: answerIndex + 1,
                  };
                }
              }
            );
            question.title = question.oldTitle;
          } catch (error) {
            throw new Error(error);
          }
        });
      });
      clearInterval(this.testTimeTimer);
      checkQuestionPaper({ data: this.paperData }).then((res) => {
        if (res.code == 200) {
          res.data.eng_question_form_vo_list.forEach((questionTypeList) => {
            questionTypeList.question_list.forEach((question) => {
              question.isAnswer = true;
              question.isTrue = question.is_true;
              question.questionId = question.id;
              question.answerType = question.type == 1 ? 1 : 2;
              question.answerList = question.option_list.map((item) => {
                return {
                  answer_id: item.id,
                  answer: item.answer,
                };
              });
              question.studentAnswer = question.stu_answer_list.map((item) => {
                if (question.type == 1) {
                  return item.answer_id;
                } else {
                  return item.answer;
                }
              });
              question.trueAnswer = question.option_list
                .filter((item) => {
                  if (question.type == 1) {
                    return item.is_true == 1;
                  } else {
                    return item;
                  }
                })
                .map((item) => {
                  return {
                    answer_id: item.id,
                    answer: item.answer,
                  };
                });
              question.verifyAnswer = question.stu_answer_list.map((item) => {
                if (question.type == 1) {
                  return {
                    answer_id: item.answer_id,
                    is_true: item.is_true,
                  };
                } else {
                  return {
                    answer: item.stu_answer,
                    is_true: item.is_true,
                    order: item.order,
                  };
                }
              });
            });
          });
          res.data.eng_question_form_vo_list = res.data.eng_question_form_vo_list.sort(
            (a, b) => {
              return a.type - b.type;
            }
          );
          this.paperData = res.data;
          this.paperData.isAnswer = true;
          this.questionList = this.paperData.eng_question_form_vo_list;
          console.log(this.paperData,"this.paperData154459");
          this.dialogVisibleScore = true;
          let type;
          if (this.paperData.score == 100) {
            type = 7;
          } else if (this.paperData.score >= 90 && this.paperData.score <= 99) {
            type = 6;
          } else if (this.paperData.score >= 80 && this.paperData.score < 90) {
            type = 5;
          } else if (this.paperData.score >= 70 && this.paperData.score < 80) {
            type = 3;
          } else if (this.paperData.score >= 60 && this.paperData.score < 70) {
            type = 2;
          } else if (this.paperData.score < 60) {
            type = 1;
          }
          this.scoreAudioType = type;
          this.$refs.playVoiceAudio.changeType(type, true);
          this.$nextTick(() => {
            this.questionList.forEach((questionType, index) => {
              questionType.question_list.forEach((question, index2) => {
                if (
                  this.$refs[`question-${index}-${index2}`] &&
                  this.$refs[`question-${index}-${index2}`][0]
                ) {
                  this.$refs[`question-${index}-${index2}`][0].showParse = true;
                }
              });
            });
          });
          this.$forceUpdate();
        }
      });
    },
    changeStudentAnswer(studentAnswer, allIndex) {
      this.questionList.forEach((questionType) => {
        questionType.question_info_list.forEach((question) => {
          if (question.allIndex == allIndex) {
            question.studentAnswer = studentAnswer;
            return;
          }
        });
      });
    },
    watchKeyDown(e) {
      if (this.isOpenMessageBox) {
        return;
      }
      if (e.keyCode == 17) {
        if (
          this.$refs[`question${this.nowIndex}`] &&
          this.$refs[`question${this.nowIndex}`][0]
        ) {
          this.$refs[`question${this.nowIndex}`][0].playAudio();
        }
      }
      if (e.keyCode == 9) {
        if (
          this.questionType.nextType == 1 ||
          this.questionType.nextType == 2 ||
          this.questionType.nextType == 3 ||
          this.questionType.nextType == ""
        ) {
          this.stopEvent(e);
          if (
            this.questionType.nowType == 4 ||
            this.questionType.nowType == 5
          ) {
            if (
              this.$refs[`question${this.nowIndex}`] &&
              this.$refs[`question${this.nowIndex}`][0]
            ) {
              this.$refs[`question${this.nowIndex}`][0].inputBlur();
            }
          }
          if (this.nowIndex + 1 > this.allNum) {
            this.nowIndex = 0;
          } else {
            this.nowIndex++;
          }
          if (this.questionType.nowType == 3) {
            if (
              this.$refs[`question${this.nowIndex}`] &&
              this.$refs[`question${this.nowIndex}`][0]
            ) {
              this.$refs[`question${this.nowIndex}`][0].playAudio();
            }
          }
          this.qScrollToView();
        }

        if (
          this.$refs[`question${this.nowIndex}`] &&
          this.$refs[`question${this.nowIndex}`][0]
        ) {
          this.$refs[`question${this.nowIndex}`][0].inputFocus();
        }
      }
      if (
        this.questionType.nowType == 1 ||
        this.questionType.nowType == 2 ||
        this.questionType.nowType == 3
      ) {
        this.stopEvent(e);
        if (e.keyCode == 49 || e.keyCode == 97) {
          this.checkAnswer(1);
        }
        if (e.keyCode == 50 || e.keyCode == 98) {
          this.checkAnswer(2);
        }
        if (e.keyCode == 51 || e.keyCode == 99) {
          this.checkAnswer(3);
        }
        if (e.keyCode == 52 || e.keyCode == 100) {
          this.checkAnswer(4);
        }
      }

      //97-100
    },
    //阻止默认事件
    stopEvent(e) {
      if (e && e.preventDefault) {
        e.preventDefault();
      } else {
        window.event.returnValue = false;
      }
    },
    //滚动到到当前
    qScrollToView() {
      if (
        this.$refs[`question${this.nowIndex}`] &&
        this.$refs[`question${this.nowIndex}`][0]
      ) {
        this.$refs[`question${this.nowIndex}`][0].$el.scrollIntoView(false);
      }
    },
    // 1/2/3/4选择选项
    checkAnswer(num) {
      this.questionList.forEach((questionType) => {
        questionType.question_info_list.forEach((question) => {
          if (
            question.allIndex == this.nowIndex &&
            question.answer_list &&
            question.answer_list[num - 1]
          ) {
            let answer = question.answer_list[num - 1];
            if (
              this.$refs[`question${this.nowIndex}`] &&
              this.$refs[`question${this.nowIndex}`][0]
            ) {
              this.$refs[`question${this.nowIndex}`][0].studentAnswer =
                answer.word_id || answer.word_name || answer.paraphrase;
              this.$refs[`question${this.nowIndex}`][0].changeStudentAnswer();
            }
          }
        });
      });
    },
    scrollBehavior() {
      let dom = document.getElementById("app");
      const top = dom.pageYOffset || dom.scrollTop || dom.scrollTop;
      if (top > 0) {
        this.isHeaderFixed = true;
      } else {
        this.isHeaderFixed = false;
      }
    },
    inputAnswer(e, { question, index }) {
      this.questionList.forEach((questionType) => {
        questionType.question_list.forEach((item) => {
          if (item.questionId == question.questionId) {
            this.$set(item.studentAnswer, index - 1, e.target.value);
          }
        });
      });
    },
    addInputEvent() {
      console.log(15815);
      this.questionList.forEach((questionType) => {
        questionType.question_list.forEach((question) => {
          for (let i = 1; i <= question.inputNum; i++) {
            document
              .getElementById(`input-${question.questionId}-${i}`)
              .addEventListener("input", (e) => {
                this.inputAnswer(e, {
                  question,
                  index: i,
                });
              });
          }
        });
      });
    },
  },
  filters: {
    filterTime(val) {
      let hours = parseInt(val / 3600);
      if (hours < 10) {
        hours = "0" + hours;
      }
      let minutes = parseInt((val % 3600) / 60);
      if (minutes < 10) {
        minutes = "0" + minutes;
      }
      let seconds = parseInt(val % 60);
      if (seconds < 10) {
        seconds = "0" + seconds;
      }
      return hours + ":" + minutes + ":" + seconds;
    },
  },
  mounted() {
    // window.addEventListener("keydown", this.watchKeyDown);
    document
      .getElementById("app")
      .addEventListener("scroll", this.scrollBehavior);
  },
  beforeDestroy() {
    // window.removeEventListener("keydown", this.watchKeyDown);
    document
      .getElementById("app")
      .removeEventListener("scroll", this.scrollBehavior);
    clearInterval(this.testTimeTimer);
    if (this.isOpenMessageBox) {
      this.$msgbox.close();
    }
  },
  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    this.unitId = this.$route.query.unitId
      ? Number(this.$route.query.unitId)
      : null;
    this.getTestPaper();
  },
  watch: {},
  components: {
    Header,
    Question,
    PlayVoiceAudio,
  },
};
</script>

<style lang="scss" scoped>
.question {
  position: relative;
  top: 0;
  left: 0;

  .start {
    font-size: 60px;
    z-index: 99;
    position: absolute;
    top: 15px;
    left: 5px;
    
  }
}
</style>